import sketch from 'sketch';
import Document from 'sketch/dom';

const imageSourceDir = `images/${getDate()}`;

/**
 * 获取年月日字符串
 * @return {string}
 */
function getDate() {
    const date = new Date();
    return `${date.getFullYear()}${date.getMonth() + 1}${date.getDate()}`;
}

/**
 * 保存切片
 * @param id 元素ID
 * @param output 输出路径
 * @param opts  保存参数
 * @return {*}
 */
function saveSlice(id, output, opts) {
    const document = Document.getSelectedDocument();
    const layer = document.getLayerWithID(id);

    if (!output) {
        return sketch.UI.message('⚠️ 导出路径有误');
    }

    const option = opts || {};
    option['use-id-for-name'] = true;
    option['group-contents-only'] = true;
    option.scales = 3;
    option.output = `${output}/${imageSourceDir}`;

    sketch.export(layer, option);
}

/**
 * 选择保存路径
 * @return {String}
 */
function getSavePathWithPanel() {
    const home = NSHomeDirectory();

    // 打开控制面板
    const openPanel = NSOpenPanel.openPanel();
    openPanel.setCanChooseDirectories(true);
    openPanel.setCanCreateDirectories(true);
    openPanel.setDirectoryURL(NSURL.fileURLWithPath(home));

    openPanel.setTitle('选择保存路径');
    openPanel.setPrompt('Choose');
    const chooseResult = openPanel.runModal();

    if (!chooseResult) return;

    // 获取选中的路径
    return openPanel.URL().path();
}

/**
 * 保存至JSON数据
 * @param path
 * @param data
 */
function saveToJson(path, data) {
    NSString.stringWithString(
        JSON.stringify(data)
    ).writeToFile_atomically_encoding_error(path, !0, NSUTF8StringEncoding, nil);
}

export default {
    imageSourceDir,
    saveSlice,
    getSavePathWithPanel,
    saveToJson
}
